<template>
    <div class="evaluation-container">
        <el-container>
            <el-header>
                <div class="header-content">
                    <h2>评价页面</h2>
                    <div class="date-selector">
                        <el-date-picker v-model="评测日期" type="date" placeholder="选择评测日期" format="YY-MM-DD"
                            value-format="YYYY-MM-DD" @change="handleDateChange" style="width: 200px" />
                    </div>
                </div>
            </el-header>
            <el-main>
                <!-- 基础信息选择 -->
                <el-card class="info-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <span>基础信息选择</span>
                        </div>
                    </template>
                    <el-form :model="selectionForm" label-width="120px" class="selection-form">
                        <el-form-item label="牌别">
                            <el-select v-model="selectionForm.牌别" placeholder="请选择牌别" clearable
                                @change="handleBrandChange" style="width: 100%">
                                <el-option v-for="brand in brandOptions" :key="brand" :label="brand" :value="brand" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="批次">
                            <el-select v-model="selectionForm.批次" placeholder="请选择批次" clearable
                                @change="handleBatchChange" :disabled="!selectionForm.牌别" style="width: 100%">
                                <el-option v-for="batch in batchOptions" :key="batch" :label="batch" :value="batch" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="日期">
                            <el-select v-model="selectionForm.日期" placeholder="请选择日期" clearable
                                @change="handleDateSelectChange" :disabled="!selectionForm.牌别 || !selectionForm.批次"
                                style="width: 100%">
                                <el-option v-for="date in dateOptions" :key="date" :label="formatDateYY(date)"
                                    :value="date" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-card>

                <!-- 感官特征评价 -->
                <el-card class="evaluation-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <span>感官特征评价</span>
                        </div>
                    </template>
                    <el-form ref="evaluationFormRef" :model="evaluationForm" label-width="120px"
                        class="evaluation-form">
                        <el-form-item label="风格特征">
                            <el-switch v-model="evaluationForm.风格特征" active-text="是" inactive-text="否" />
                        </el-form-item>

                        <el-form-item label="香气特征">
                            <el-switch v-model="evaluationForm.香气特征" active-text="是" inactive-text="否" />
                        </el-form-item>

                        <el-form-item label="烟气特征">
                            <el-switch v-model="evaluationForm.烟气特征" active-text="是" inactive-text="否" />
                        </el-form-item>

                        <el-form-item label="口感特征">
                            <el-switch v-model="evaluationForm.口感特征" active-text="是" inactive-text="否" />
                        </el-form-item>

                        <el-form-item label="特殊质量">
                            <el-switch v-model="evaluationForm.特殊质量" active-text="是" inactive-text="否" />
                        </el-form-item>

                        <el-form-item label="结论">
                            <el-switch v-model="evaluationForm.结论" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-form>
                </el-card>

                <!-- 缺陷描述 -->
                <el-card class="defect-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <span>缺陷描述</span>
                        </div>
                    </template>
                    <el-form ref="defectFormRef" :model="defectForm" label-width="120px" class="defect-form">
                        <el-form-item label="盒装缺陷">
                            <el-switch v-model="defectForm.盒装缺陷" active-text="是" inactive-text="否" />
                        </el-form-item>

                        <el-form-item label="卷制缺陷">
                            <el-switch v-model="defectForm.卷制缺陷" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-form>
                </el-card>

                <!-- 提交按钮 -->
                <div class="submit-section">
                    <el-button type="primary" :loading="loading" @click="handleSubmit" style="width: 100%" size="large">
                        提交评价
                    </el-button>
                </div>

                <div class="nav-section">
                    <el-button type="info" @click="goToBasicInfo" style="width: 100%">
                        返回基础信息页面
                    </el-button>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
    getEvaluationByDate,
    updateEvaluation,
    getBrandsByDate,
    getBatchesByDateAndBrand,
    getDatesByDateBrandAndBatch,
    getDefectByDate,
    saveDefect
} from '../api/api';

const router = useRouter();
const evaluationFormRef = ref(null);
const defectFormRef = ref(null);
const loading = ref(false);
const 评测日期 = ref('');
const brandOptions = ref([]);
const batchOptions = ref([]);
const dateOptions = ref([]);

const selectionForm = reactive({
    牌别: '',
    批次: '',
    日期: ''
});

const evaluationForm = reactive({
    风格特征: false,
    香气特征: false,
    烟气特征: false,
    口感特征: false,
    特殊质量: false,
    结论: false
});

const defectForm = reactive({
    盒装缺陷: false,
    卷制缺陷: false
});

// 格式化日期为YY-MM-DD格式
const formatDateYY = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear().toString().slice(-2);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 获取今天的日期
const getToday = () => {
    const today = new Date();
    评测日期.value = today.toISOString().split('T')[0];
};

// 评测日期变化
const handleDateChange = async () => {
    if (!评测日期.value) return;

    // 重置选择
    selectionForm.牌别 = '';
    selectionForm.批次 = '';
    selectionForm.日期 = '';
    batchOptions.value = [];
    dateOptions.value = [];

    // 加载牌别选项
    await loadBrands();

    // 重置评价表单和缺陷表单
    resetEvaluationForm();
};

// 加载牌别选项
const loadBrands = async () => {
    if (!评测日期.value) return;

    try {
        const res = await getBrandsByDate(评测日期.value);
        if (res.success) {
            brandOptions.value = res.data || [];
        } else {
            ElMessage.error(res.message || '获取牌别选项失败');
        }
    } catch (error) {
        console.error('获取牌别选项失败:', error);
        ElMessage.error('获取牌别选项失败，请重试');
    }
};

// 牌别变化
const handleBrandChange = async () => {
    selectionForm.批次 = '';
    selectionForm.日期 = '';
    dateOptions.value = [];

    if (!评测日期.value || !selectionForm.牌别) {
        batchOptions.value = [];
        return;
    }

    try {
        const res = await getBatchesByDateAndBrand(评测日期.value, selectionForm.牌别);
        if (res.success) {
            batchOptions.value = res.data || [];
        } else {
            ElMessage.error(res.message || '获取批次选项失败');
        }
    } catch (error) {
        console.error('获取批次选项失败:', error);
        ElMessage.error('获取批次选项失败，请重试');
    }

    // 重置评价表单
    resetEvaluationForm();
};

// 批次变化
const handleBatchChange = async () => {
    selectionForm.日期 = '';

    if (!评测日期.value || !selectionForm.牌别 || !selectionForm.批次) {
        dateOptions.value = [];
        return;
    }

    try {
        const res = await getDatesByDateBrandAndBatch(评测日期.value, selectionForm.牌别, selectionForm.批次);
        if (res.success) {
            dateOptions.value = res.data || [];
            // 如果只有一个选项，自动选中
            if (dateOptions.value.length === 1) {
                selectionForm.日期 = dateOptions.value[0];
                await handleDateSelectChange();
            }
        } else {
            ElMessage.error(res.message || '获取日期选项失败');
        }
    } catch (error) {
        console.error('获取日期选项失败:', error);
        ElMessage.error('获取日期选项失败，请重试');
    }

    // 重置评价表单
    resetEvaluationForm();
};

// 日期选择变化 - 加载评价数据和缺陷数据
const handleDateSelectChange = async () => {
    if (!评测日期.value || !selectionForm.牌别 || !selectionForm.批次 || !selectionForm.日期) {
        resetEvaluationForm();
        return;
    }

    await loadEvaluation();
    await loadDefect();
};

// 加载评价信息
const loadEvaluation = async () => {
    if (!评测日期.value || !selectionForm.牌别 || !selectionForm.批次) {
        resetEvaluationForm();
        return;
    }

    try {
        const res = await getEvaluationByDate(评测日期.value, selectionForm.牌别, selectionForm.批次);
        if (res.success && res.data.length > 0) {
            const data = res.data[0];
            evaluationForm.风格特征 = Boolean(data.风格特征);
            evaluationForm.香气特征 = Boolean(data.香气特征);
            evaluationForm.烟气特征 = Boolean(data.烟气特征);
            evaluationForm.口感特征 = Boolean(data.口感特征);
            evaluationForm.特殊质量 = Boolean(data.特殊质量);
            evaluationForm.结论 = Boolean(data.结论);
        } else {
            // 如果没有数据，重置表单
            resetEvaluationForm();
        }
    } catch (error) {
        console.error('获取评价信息失败:', error);
        resetEvaluationForm();
    }
};

// 加载缺陷描述
const loadDefect = async () => {
    if (!评测日期.value) {
        defectForm.盒装缺陷 = false;
        defectForm.卷制缺陷 = false;
        return;
    }

    try {
        const res = await getDefectByDate(评测日期.value);
        if (res.success && res.data) {
            defectForm.盒装缺陷 = Boolean(res.data.盒装缺陷);
            defectForm.卷制缺陷 = Boolean(res.data.卷制缺陷);
        } else {
            defectForm.盒装缺陷 = false;
            defectForm.卷制缺陷 = false;
        }
    } catch (error) {
        console.error('获取缺陷描述失败:', error);
        defectForm.盒装缺陷 = false;
        defectForm.卷制缺陷 = false;
    }
};

// 重置评价表单
const resetEvaluationForm = () => {
    evaluationForm.风格特征 = false;
    evaluationForm.香气特征 = false;
    evaluationForm.烟气特征 = false;
    evaluationForm.口感特征 = false;
    evaluationForm.特殊质量 = false;
    evaluationForm.结论 = false;
};

// 提交评价
const handleSubmit = async () => {
    if (!评测日期.value || !selectionForm.牌别 || !selectionForm.批次 || !selectionForm.日期) {
        ElMessage.warning('请先选择完整的基础信息');
        return;
    }

    loading.value = true;
    try {
        // 提交评价表
        const evaluationRes = await updateEvaluation({
            评测日期: 评测日期.value,
            牌别: selectionForm.牌别,
            批次: selectionForm.批次,
            风格特征: evaluationForm.风格特征,
            香气特征: evaluationForm.香气特征,
            烟气特征: evaluationForm.烟气特征,
            口感特征: evaluationForm.口感特征,
            特殊质量: evaluationForm.特殊质量,
            结论: evaluationForm.结论
        });

        // 提交缺陷描述
        const defectRes = await saveDefect({
            评测日期: 评测日期.value,
            盒装缺陷: defectForm.盒装缺陷,
            卷制缺陷: defectForm.卷制缺陷
        });

        if (evaluationRes.success && defectRes.success) {
            ElMessage.success('评价提交成功！');
        } else {
            ElMessage.error('提交失败，请重试');
        }
    } catch (error) {
        ElMessage.error(error.message || '提交失败，请重试');
    } finally {
        loading.value = false;
    }
};

// 前往基础信息页面
const goToBasicInfo = () => {
    router.push('/basic-info');
};

onMounted(async () => {
    getToday();
    await handleDateChange();
});
</script>

<style scoped>
.evaluation-container {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.el-header {
    background-color: #409eff;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 20px;
}

.header-content {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-content h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
}

.date-selector {
    display: flex;
    align-items: center;
}

.el-main {
    padding: 20px;
}

.info-card,
.evaluation-card,
.defect-card {
    margin-bottom: 20px;
}

.card-header {
    font-weight: 500;
    font-size: 16px;
}

.selection-form {
    padding: 10px 0;
}

.evaluation-form,
.defect-form {
    padding: 10px 0;
}

.submit-section,
.nav-section {
    margin-top: 20px;
    max-width: 500px;
    margin-left: auto;
    margin-right: auto;
}

@media (max-width: 768px) {
    .el-main {
        padding: 15px;
    }

    .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .date-selector {
        width: 100%;
    }

    .info-card,
    .evaluation-card,
    .defect-card {
        margin-bottom: 15px;
    }
}
</style>
